﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IceDog.Lib.Poker.PokerEventHandler;

namespace IceDog.Lib.Poker.PokerClient
{
    public class Game
    {

        public Game()
        {
            _currentCard = 1;
            _discardedCardList = new CardList();
            _playDeck = new Deck(true);
            _playDeck.Shuffle();
            _playDeck.LastCardDrawn += delegate (object sender, LastCardDrawnEventHandler e)
            {
                Console.WriteLine("清空牌堆 重新洗牌。");
                (sender as Deck).Shuffle();
                _discardedCardList.Clear();
                _currentCard = 1;
            };
            _winner = -1;
            _gameWin = false;
        }
        /// <summary>
        /// 要使用的一副牌
        /// </summary>
        private Deck _playDeck;
        /// <summary>
        /// 当前的牌
        /// </summary>
        private int _currentCard;
        /// <summary>
        /// 玩家列表
        /// </summary>
        private List<Player> _playerList;
        /// <summary>
        /// 使用过的牌
        /// </summary>
        private CardList _discardedCardList;
        /// <summary>
        /// 临时卡牌，用于临时存储翻开的牌和丢弃进废弃牌堆的牌
        /// </summary>
        private Card _tempCard;
        /// <summary>
        /// 用于存储胜利者的索引值(默认值-1)
        /// </summary>
        private int _winner;
        private readonly int _winnerError=-1;
        private readonly int _winnerIsNone = -2;
        /// <summary>
        /// 表示是否有玩家胜利
        /// </summary>
        private bool _gameWin;
        /// <summary>
        /// 设置玩家集合
        /// </summary>
        /// <param name="playerList"></param>
        public void SetPlayerList(List<Player> playerList)
        {
            if (playerList.Count > 7 || playerList.Count < 2)
            {
                throw new ArgumentOutOfRangeException("值的范围只能在2和7之间(包括2和7)");
            }
            else
            {
                _playerList = playerList;
            }
        }
        /// <summary>
        /// 给每个玩家发7张牌
        /// </summary>
        public void DealHands()
        {
            _playerList.ForEach(p =>
            {
                int i = 7;
                while (i-- != 0)
                {
                    p.PlayHand.Add(_playDeck.GetCard(_currentCard++));
                }
            });
        }

        private int DoEveryPlayerLogic(Player player)
        {
            Console.WriteLine("轮到玩家 {0}", player.Name);
            Console.WriteLine("当前手牌：");
            player.PlayHand.Sort(Card.Comparer.Default);
            player.PlayHand.ForEach(c => Console.WriteLine(c.ToChineseString()));
            Console.WriteLine("现在桌面上翻开的牌：{0}", _tempCard.ToChineseString());
            var input = Helper.GetRightInput("按T键把桌面上的牌放进手牌 按D键舍弃桌面上的然后拿一张新牌", new[] { "t", "d" });
            if (input.ToLower().Equals("t"))
            {
                Console.WriteLine("把 {0} 放入手牌", _tempCard);
                if (_discardedCardList.Contains(_tempCard))
                {
                    _discardedCardList.Remove(_tempCard);
                }
                player.PlayHand.Add(_tempCard);
            }
            else if (input.ToLower().Equals("d"))
            {
                bool cardIsAvailable;
                Card newCard;
                do
                {
                    newCard = _playDeck.GetCard(_currentCard++);
                    cardIsAvailable = !_discardedCardList.Contains(newCard);
                    if (cardIsAvailable)
                    {
                        _playerList.ForEach(p2 =>
                        {
                            if (p2.PlayHand.Contains(newCard))
                            {
                                cardIsAvailable = false;
                            }
                        });
                    }
                } while (!cardIsAvailable);
                Console.WriteLine("新牌为 {0} ，放入手牌", newCard.ToChineseString());
                player.PlayHand.Add(newCard);
            }
            Console.WriteLine("现在的手牌：");
            var i = 1;
            var condition = new string[8];
            player.PlayHand.ForEach(c =>
            {
                condition[i - 1] = i.ToString();
                Console.WriteLine("{0} : {1}", i++, c.ToChineseString());
            });
            input = Helper.GetRightInput("选择要扔掉的手牌牌(输入编号)：", condition);
            var choice = -1;
            try
            {
                choice = int.Parse(input);
            }
            catch
            {
                throw;
            }
            _tempCard = player.PlayHand[choice - 1];
            player.PlayHand.RemoveAt(choice - 1);
            _discardedCardList.Add(_tempCard);
            Console.WriteLine("丢弃的牌：{0}", _tempCard.ToChineseString());
            Console.WriteLine();
            _gameWin = player.HasWin();
            if (_gameWin)
            {
                _winner = _playerList.IndexOf(player);
                return _winner;
            }
            return _winnerIsNone;
        }
        /// <summary>
        /// 进行游戏主循环
        /// </summary>
        /// <returns></returns>
        public int PlayGame()
        {
            if (_playerList == null)
            {
                return _winnerError;
            }
            this.DealHands();
            //开局翻开一张牌
            _tempCard = _playDeck.GetCard(_currentCard++);
            _discardedCardList.Add(_tempCard);
            do
            {
                foreach (var p in _playerList)
                {
                    Console.WriteLine("------------------------------------------");
                    var res = this.DoEveryPlayerLogic(p);
                    if (res!= _winnerIsNone)
                    {
                        return res;
                    }
                }
            } while (!_gameWin);
            return _winner;
        }
    }
}
